<?php

namespace StudyBuddy\Controllers;

use StudyBuddy\WebPage;
use \StudyBuddy\Request;
use \StudyBuddy\Responder;
use StudyBuddy\Cookie;
use \StudyBuddy\ExternalAuthFb;

/**
 *
 * Controller processes Ajax request to
 * connect Facebook account (to existing Viewer account)
 * 
 * This Controller is called ONLY via Ajax!
 *
 */
class Connectfb extends WebPage
{
	/**
	 *
	 * Only logged in user can use this controller
	 *
	 * @var bool
	 */
	protected $membersOnly = true;


	/**
	 * (non-PHPdoc)
	 * @see StudyBuddy.WebPage::main()
	 */
	protected function main(){
                
            d('Re login Facebook User');
//            $_COOKIE['fbsr_studybuddy'] = '';
            Cookie::set('fbsr_studybuddy', '');

		try{
			d('cp');
			ExternalAuthFb::factory($this->oRegistry)->connect($this->oRegistry->Viewer);
			d('cp');
		} catch (\StudyBuddy\FacebookAuthException $e ){
			d('Caught FacebookAuthException');
			/**
			 * Something went wrong with cookie validation
			 * or there was no facebook auth cookie
			 */
			if($e instanceof \StudyBuddy\FacebookAuthUserException){
				d('caught FacebookAuthUserException');

				throw $e;
			}
			
			e('Unable to connect Facebook account. '.$e->getMessage.' in file '.$e->getFile().' on line '.$e->getLine());
			throw new \StudyBuddy\Exception('Unable to connect Facebook account at this time');
		}

		d('cp');
		
		$this->respond();
	}


	/**
	 * Send Ajax based reponse
	 * 
	 */
	protected function respond(){

		$aRet = array('setmeta' => array('key' => 'fb', 'val' => '1'),
		'replace' => array('target' => 'my_fb', 'content' => $this->oRegistry->Viewer->getFacebookUrl()));
		d('sending out JSON: '.print_r($aRet, 1));

		Responder::sendJSON($aRet);
	}
}
